import Vue from 'vue'
import Vuex from 'vuex'
import auth from '@/services/auth'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: null
  },
  getters: {
    isAuthenticated: state => !!state.user,
    user: state => state.user
  },
  mutations: {
    setUser(state, user) {
      state.user = user
    },
    clearUser(state) {
      state.user = null
    }
  },
  actions: {
    async login({ commit }) {
      await auth.login()
    },
    async logout({ commit }) {
      await auth.logout()
      commit('clearUser')
    },
    async handleCallback({ commit }) {
      const user = await auth.handleCallback()
      commit('setUser', user)
      return user
    },
    async checkAuth({ commit }) {
      const user = await auth.getUser()
      if (user) {
        commit('setUser', user)
      }
      return user
    }
  }
}) 